﻿using System;
using System.Threading.Tasks;
using OpenAiClient.Tools;
using OpenAiClient.Util.Database;
using OpenAiClient.Util.Extensions;

namespace OpenAiClient.Services
{
    // ReSharper disable IdentifierTypo
    public class SqliteService : ISqliteService
    {
        private readonly string _connectionString;
        private readonly ILogService _logService;

        public SqliteService(
            ILogService logService,
            IConfigService configService
        )
        {
            _logService = logService;
            _connectionString = Constants.SQLite.GetConnectionString(configService.AppDataDirectory);
        }

        public void PrepareSqlite()
        {
            Task.Run(async () => await PrepareSqliteAsync());
        }

        private async Task PrepareSqliteAsync()
        {
            var sqliteHelper = new SqliteHelper() { ConnectionString = _connectionString };
            await PrepareDatabaseAsync(sqliteHelper); //创建数据库
            await CreateTablesAsync(sqliteHelper); //创建表
        }

        private async Task PrepareDatabaseAsync(SqliteHelper sqliteHelper)
        {
            try
            {
                await sqliteHelper.PrepareDatabaseAsync();
            }
            catch (Exception e)
            {
                // ReSharper disable once StringLiteralTypo
                _logService.Error($@"SqliteService PrepareDatabaseAsync Exception: {e.GetFullMessage()}.");
            }
        }

        private async Task CreateTablesAsync(SqliteHelper sqliteHelper)
        {
            try
            {
                //历史记录表
                var sql = @"CREATE TABLE IF NOT EXISTS History(
	                            Id VARCHAR(32) PRIMARY KEY,
	                            Question VARCHAR(256) NOT NULL,
                                Answer TEXT,
	                            ErrorMessage TEXT,
                                IsSuccess TINYINT NOT NULL,
	                            CreateTime TEXT NOT NULL
                            );";
                await sqliteHelper.ExecuteNonQueryAsync(sql);
            }
            catch (Exception e)
            {
                // ReSharper disable once StringLiteralTypo
                _logService.Error($@"SqliteService CreateTablesAsync Exception: {e.GetFullMessage()}.");
            }
        }
    }
}
